package com.net.wanjian.networkhospitalmanager.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.joooonho.SelectableRoundedImageView;
import com.net.wanjian.networkhospitalmanager.MyApplication;
import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.skilltrain.SkillTrainActivity;
import com.net.wanjian.networkhospitalmanager.adapter.base.RecyclerBaseAdapter;
import com.net.wanjian.networkhospitalmanager.bean.LabReserveListReturn;
import com.net.wanjian.networkhospitalmanager.bean.StudentApplyReserveReturn;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.consts.LabReserveBtnConst;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.utils.PicassoUtil;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.TimeDateUtils;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.zhy.autolayout.utils.AutoUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.observers.DisposableObserver;

/**
 * Description:
 * Created by lidongcai on 17/4/27.
 * Email:  lidongcaiocc@163.com
 */

public class LabReserveListAdapter extends RecyclerBaseAdapter<LabReserveListReturn.DataBean.LabReserveListBean, LabReserveListAdapter.ViewHolder> {
//    private SkillTrainActivity activity;
    private LocalBroadcastManager localBroadcastManager;

    public LabReserveListAdapter(Context context) {
        super(context);
//        this.activity = (SkillTrainActivity) context;
        localBroadcastManager = LocalBroadcastManager.getInstance(context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_labreserve_list, parent, false);
        AutoUtils.auto(view);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final LabReserveListReturn.DataBean.LabReserveListBean d, final int position) {
        //设置实验名称
        holder.setLabNameTv(URLDecoderUtil.getDecoder(d.getLabReserveName()));
        //获取当前人数和最大人数
        String currentPNum = URLDecoderUtil.getDecoder(d.getLabReserveCurrentPerson());
        String maxPNum = URLDecoderUtil.getDecoder(d.getLabReserveMaxPerson());
        holder.setLabNumberTv("名额：" + currentPNum + "/" + maxPNum);
        //是否存在指导教师（0不存在，1存在）
        if (URLDecoderUtil.getDecoder(d.getIsExistGuideTeacher()).equals("0")) {
            holder.setLabIsGuideTeacherIv(false);
        } else {
            holder.setLabIsGuideTeacherIv(true);
        }
        //技能名称集合（中间以英文逗号隔开）
        holder.setLabSkillTv("练习技能："+URLDecoderUtil.getDecoder(d.getTrainTypeNameArray()));
        //截止时间
        holder.setLabStopTimeTv("截止时间：" + TimeDateUtils.formatTimeFriend(URLDecoderUtil.getDecoder(d.getLabReserveEndTime())));
        //设置开放到关闭的时间，需要格式化
        String openTime = TimeDateUtils.formatTimeFriend(URLDecoderUtil.getDecoder(d.getLabReserveOpenTime()));
        String closeTime = TimeDateUtils.formatTimeFriend(URLDecoderUtil.getDecoder(d.getLabReserveCloseTime()));
        String ot = openTime.split(" ")[0];
        String ct = closeTime.split(" ")[0];
        if (ot.equals(ct)) {
            holder.setLabStartTimeTv(openTime + "—" + closeTime.split(" ")[1]);
        } else {
            holder.setLabStartTimeTv(openTime + "—" + closeTime);
        }


        //设置按钮的状态
        if (SharedXmlUtil.getInstance().getUserIdentity().equals("1")) {
            holder.setLabReserveBtn(LabReserveBtnConst.NO_RESERVED);
        } else {
            //非老师预约按钮的状态
            //人数小于总人数允许预约，否则不允许
            if (Integer.parseInt(currentPNum) < Integer.parseInt(maxPNum)) {
                holder.setLabReserveBtn(LabReserveBtnConst.CAN_RESERVED);
            } else {
                holder.setLabReserveBtn(LabReserveBtnConst.UNABLE_RESERVED);
            }
        }

        holder.labReserveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpUtil.studentApplyReserve(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                        SharedXmlUtil.getInstance().getHospitalId(), SharedXmlUtil.getInstance().getUserIdentityId(), d.getLabReserveID(), new DisposableObserver<StudentApplyReserveReturn>() {
                            @Override
                            public void onNext(StudentApplyReserveReturn studentApplyReserveReturn) {
                                if (studentApplyReserveReturn.getResult().equals("1")){
                                    ToastUtil.showToast("预约成功，请到我的预约中进行查看");
                                    list.remove(position);
                                    notifyDataSetChanged();
                                    //通知刷新学生预约列表
//                                    activity.refreshStudentReserveList();
                                    localBroadcastManager.sendBroadcast(new Intent("refreshmyreservation"));

                                }else {
                                    switch (Integer.parseInt(studentApplyReserveReturn.getResult())){
                                        case ErrorCodeReturn.personLimit:
                                            ToastUtil.showToast("预约人数已达上限");
                                            break;
                                        case ErrorCodeReturn.excessStopTime:
                                            ToastUtil.showToast("已经过了预约截止时间");
                                            break;
                                        case ErrorCodeReturn.orderCancel:
                                            ToastUtil.showToast("实验预约已经取消");
                                            break;
                                        case ErrorCodeReturn.userIsBlackList:
                                            ToastUtil.showToast("您已经被加入黑名单，无法预约");
                                            break;
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        });

    }


    public static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.lab_name_tv)
        TextView labNameTv;
        @BindView(R.id.lab_skill_tv)
        TextView labSkillTv;
        @BindView(R.id.lab_number_tv)
        TextView labNumberTv;
        @BindView(R.id.lab_stop_time_tv)
        TextView labStopTimeTv;
        @BindView(R.id.lab_num_time_layout)
        LinearLayout labNumTimeLayout;
        @BindView(R.id.lab_start_time_tv)
        TextView labStartTimeTv;
        @BindView(R.id.lab_is_guide_teacher_iv)
        SelectableRoundedImageView labIsGuideTeacherIv;
        @BindView(R.id.relativeLayout)
        RelativeLayout relativeLayout;
        @BindView(R.id.lab_reserve_btn)
        Button labReserveBtn;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }


        public void setLabNameTv(String labNameTv) {
            this.labNameTv.setText(labNameTv);
        }

        public void setLabSkillTv(String labSkillTv) {
            this.labSkillTv.setText(labSkillTv);
        }

        public void setLabNumberTv(String labNumberTv) {
            this.labNumberTv.setText(labNumberTv);
        }

        public void setLabStopTimeTv(String labStopTimeTv) {
            this.labStopTimeTv.setText(labStopTimeTv);
        }

        public void setLabNumTimeLayout() {
//            this.labNumTimeLayout = labNumTimeLayout;
        }

        public void setLabStartTimeTv(String labStartTimeTv) {
            this.labStartTimeTv.setText(labStartTimeTv);
        }

        public void setLabIsGuideTeacherIv(boolean b) {
            if (b) {
                labIsGuideTeacherIv.setBackgroundResource(R.mipmap.practice_btn_green);
            } else {
                labIsGuideTeacherIv.setBackgroundResource(R.mipmap.practice_btn_grey);
            }
        }


        public void setLabReserveBtn(int type) {
            switch (type) {
                case LabReserveBtnConst.NO_RESERVED:
                    labReserveBtn.setVisibility(View.GONE);
                    break;
                case LabReserveBtnConst.UNABLE_RESERVED:
                    labReserveBtn.setEnabled(false);
                    labReserveBtn.setText("立即预约");
                    labReserveBtn.setBackgroundResource(R.drawable.lab_reserve_btn_color);
                    break;
                case LabReserveBtnConst.CAN_RESERVED:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("立即预约");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
                case LabReserveBtnConst.CANCEL_RESERVED:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("取消预约");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
                case LabReserveBtnConst.WAIT_OPEN:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("等待开放");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
                case LabReserveBtnConst.ENTER_LAB:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("进入实验室");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
                case LabReserveBtnConst.SERVER_CANCEL:
                    labReserveBtn.setEnabled(false);
                    labReserveBtn.setText("立即预约");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
                case LabReserveBtnConst.RECEIPT:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("回执");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
            }
        }
    }

}
